"use strict";

// chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//   console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
//   const { cb, cookie, config } = request;
//   sendResponse(this[cb].call(this, cookie, config));
// });

addCookiesChangeEvent();

function addCookiesChangeEvent() {
  console.log("addCookiesChangeEvent");
  chrome.cookies.onChanged.addListener(async ({ cookie, removed }) => {
    const { domainList: domainObj } = await chrome.storage.local.get(["domainList"]);
    const storageList = Object.keys(domainObj).map(key => domainObj[key]);
    const target = storageList.find(
      e => equalDomain(e.from, cookie.domain) && e.name === cookie.name
    );
    console.log("target", target);
    if (target) {
      // 移除
      if (removed) removeCookie(cookie, target);
      // 设置、更新
      else setCookie(cookie, target);
    }
  });
}

function setCookie(cookie, config) {
  chrome.cookies.set({
    url: addProtocol(config.to),
    domain: removeProtocol(config.to),
    name: cookie["name"],
    path: cookie["path"],
    value: cookie["value"],
    // expirationDate: cookie["expirationDate"],
    // secure: true,
    // sameSite: "no_restriction", // 不阻止跨域cookie
  });
}

function removeCookie(cookie, config) {
  chrome.cookies.remove({
    url: addProtocol(config.to),
    name: cookie["name"],
  });
}
// 增加协议头
function addProtocol(uri) {
  return uri.startsWith("http") ? uri : "http://" + uri;
}
// 去除协议头
function removeProtocol(uri) {
  return uri.startsWith("http") ? uri.replace("https://", "").replace("http://", "") : uri;
}

function equalDomain(domain1, domain2) {
  return addProtocol(domain1) === addProtocol(domain2);
}
